package com.demo.product.controller;

import com.demo.product.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 秒杀控制器
 * 提供秒杀相关的API接口
 */
@RestController
@RequestMapping("/api/seckill")
public class SeckillController {

    private static final Logger log = LoggerFactory.getLogger(SeckillController.class);

    @Autowired
    private SeckillService seckillService;

    /**
     * 开始秒杀
     * @param productId 商品ID
     * @param userId 用户ID（实际项目中应该从token中获取）
     * @param quantity 购买数量
     * @return 秒杀结果
     */
    @PostMapping("/start/{productId}")
    public Map<String, Object> startSeckill(
            @PathVariable Long productId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") Integer quantity) {
        
        log.info("开始秒杀，userId: {}, productId: {}, quantity: {}", userId, productId, quantity);
        
        try {
            return seckillService.doSeckill(userId, productId, quantity);
        } catch (Exception e) {
            log.error("秒杀接口异常，userId: {}, productId: {}", userId, productId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
            return result;
        }
    }

    /**
     * 查询商品库存
     * @param productId 商品ID
     * @return 库存信息
     */
    @GetMapping("/stock/{productId}")
    public Map<String, Object> getStock(@PathVariable Long productId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Integer stock = seckillService.getCurrentStock(productId);
            result.put("success", true);
            result.put("productId", productId);
            result.put("stock", stock);
            result.put("message", "查询成功");
        } catch (Exception e) {
            log.error("查询库存异常，productId: {}", productId, e);
            result.put("success", false);
            result.put("message", "查询失败");
        }
        
        return result;
    }

    /**
     * 初始化商品库存（管理员接口）
     * @param productId 商品ID
     * @param stock 库存数量
     * @return 操作结果
     */
    @PostMapping("/init-stock")
    public Map<String, Object> initStock(
            @RequestParam Long productId,
            @RequestParam Integer stock) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (stock <= 0) {
                result.put("success", false);
                result.put("message", "库存数量必须大于0");
                return result;
            }
            
            seckillService.initStock(productId, stock);
            result.put("success", true);
            result.put("message", "库存初始化成功");
            result.put("productId", productId);
            result.put("stock", stock);
            
            log.info("库存初始化成功，productId: {}, stock: {}", productId, stock);
            
        } catch (Exception e) {
            log.error("库存初始化异常，productId: {}, stock: {}", productId, stock, e);
            result.put("success", false);
            result.put("message", "库存初始化失败");
        }
        
        return result;
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "seckill-service");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
}